<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function Axios(config) {
        this.config = config
    }

    Axios.prototype.request = function (config) {
        // 创建一个promise对象
        let promise = Promise.resolve(config)
        // 声明一个数组
        let chain = [dispatchRequest, undefined]
        // 调用then方法指定回调
        let result = promise.then(chain[0], chain[1]);
        // 返回promise的结果
        return result
    }

    function dispatchRequest(config) {
        // 调用适配器发送请求
        return xhrAdapter(config).then(value => {
            // 响应结果处理和转换
            return value
        }, reason => {
            throw reason
        })
    }

    function xhrAdapter(config) {
        return new Promise(((resolve, reject) => {
            let xhr = new XMLHttpRequest()
            xhr.open(config.method, config.url)
            xhr.send()
            xhr.responseType = 'json'
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve({
                            config: config,
                            data: xhr.response,
                            headers: xhr.getAllResponseHeaders(),
                            request: xhr,
                            status: xhr.status,
                            statusText: xhr.statusText
                        })
                    } else {
                        reject(new Error('请求失败，失败的状态码为：' + xhr.status))
                    }
                }
            }
        }))
    }

    let axios = Axios.prototype.request

    axios({
        method: 'get',
        url: 'http://127.0.0.1:3000/posts'
    }).then(value => {
        console.log(value)
    })


</script>
</body>
</html>